package com.jeomo.common.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * <h3>jeomo</h3>
 * <p>类工具</p>
 *
 * @author : qibotian
 * @date : 2020-09-28 11:03
 **/
public class ClassUtil extends cn.hutool.core.util.ClassUtil {

    /**
     * 获取某个字段的值
     * @param obj
     * @param fieldName
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static Object getFiledValue(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        if(obj == null) { return  null; }
        Class<?> clazz = obj.getClass();
        try {
            Method getMethod = getGetMethod(clazz, fieldName);
            return getMethod.invoke(obj);
        } catch (NoSuchMethodException e) {
            Field parentField = clazz.getDeclaredField(fieldName);
            return parentField.get(obj);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Method getGetMethod(Class clazz, String fieldName) throws NoSuchMethodException {
        String s = fieldName.substring(0, 1);
        String fix = fieldName.substring(1, fieldName.length());
        String methodName = "get"+s.toUpperCase()+fix;
        return clazz.getMethod(methodName);
    }


    public static boolean hasGetMethod(Class clazz, String fieldName) {
        String s = fieldName.substring(0, 1);
        String fix = fieldName.substring(1, fieldName.length());
        String methodName = "get"+s.toUpperCase()+fix;
        try {
            clazz.getMethod(methodName);
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    /**
     * 获取带有某个注解的所有字段
     * @param clazz
     * @param annocationClass
     * @return
     */
    public static List<Field> getFieldsListWithAnnotation(Class clazz, Class annocationClass) {
        Field[] fields = clazz.getDeclaredFields();
        List<Field> result = new ArrayList<>();
        for(Field field : fields) {
            if(field.isAnnotationPresent(annocationClass)) {
                result.add(field);
            }
        }
        return result;
    }

    /**
     * 设置某个字段的值
     * @param obj
     * @param fieldName
     * @param value
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static Object setFiledValue(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        if(obj == null) { return  null; }
        Class<?> clazz = obj.getClass();
        Field parentField = clazz.getDeclaredField(fieldName);
        parentField.setAccessible(true);
        parentField.set(obj, value);
        return parentField.get(obj);
    }
}
